package com.helloaps.web.controller.scheduling;

import ai.timefold.solver.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import ai.timefold.solver.core.api.solver.SolutionManager;
import ai.timefold.solver.core.api.solver.SolverManager;
import ai.timefold.solver.core.api.solver.SolverStatus;
import com.helloaps.common.core.controller.BaseController;
import com.helloaps.common.core.domain.AjaxResult;
import com.helloaps.scheduling.domain.ProductionSchedule;
import com.helloaps.scheduling.service.IDemoDataGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 排程测试用
 *
 * @author zhq
 */
@RestController
@RequestMapping("/scheduling/demo")
public class DemoDataController extends BaseController
{
    public static final String SINGLETON_SOLUTION_ID = "1";

    @Autowired
    private SolverManager<ProductionSchedule, String> solverManager;
    @Autowired
    private SolutionManager<ProductionSchedule, HardMediumSoftLongScore> solutionManager;
    @Autowired
    private IDemoDataGenerator demoDataGenerator;

    @GetMapping
    public AjaxResult get()
    {
        // 加载测试数据，同时把当前的状态返回给前端，防止重复执行优化
        SolverStatus solverStatus = solverManager.getSolverStatus(SINGLETON_SOLUTION_ID);
        ProductionSchedule schedule = demoDataGenerator.getDemoData();
        schedule.setSolverStatus(solverStatus);
        return success(schedule);
    }

    @GetMapping(value = "/status")
    public AjaxResult status()
    {
        SolverStatus solverStatus = solverManager.getSolverStatus(SINGLETON_SOLUTION_ID);
        return success(solverStatus);
    }

    @PostMapping
    public AjaxResult solve()
    {
        solverManager.solveBuilder()
                .withProblemId(SINGLETON_SOLUTION_ID)
                .withProblemFinder(id -> demoDataGenerator.getDemoData())
                .withBestSolutionConsumer(schedule -> demoDataGenerator.setDemoData(schedule))
                .run();
        return success();
    }

    @PostMapping(value = "/stop")
    public AjaxResult stop()
    {
        solverManager.terminateEarly(SINGLETON_SOLUTION_ID);
        return success();
    }
}
